package struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.form.ActionForm;
import struts.form.FullForm;
import struts.form.XmlBean;

public class ActionServlet extends HttpServlet {

	private static final long serialVersionUID = 6235869112804863934L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String path=getPath(request.getServletPath());
		Map<String,XmlBean> map=(Map<String,XmlBean>)this.getServletContext().getAttribute("struts");
		XmlBean xml=map.get(path);
		String beanName=xml.getBeanClass();
		ActionForm form=FullForm.full(beanName, request);
		String actionType=xml.getActionType();
		String url="";
		
		Class clazz;
		try {
			clazz = Class.forName(actionType);
			Action action = (Action)clazz.newInstance();
			url=action.execute(request, form, xml.getForward());
		} catch (Exception e) {
			e.printStackTrace();
		}
		RequestDispatcher dis=request.getRequestDispatcher(url);
		dis.forward(request, response);
	
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
	
	private String getPath(String path){
		return path.split("\\.")[0];
	}
}
